import com.world.common.util.SysUtil;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import org.junit.Test;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Modifier;

/**
 * Created by gang on 2016/10/13.
 */
public class ApiDocUtils {
    private String url = "http://127.0.0.1/";

    @Test
    public void list() throws Exception {
        System.out.println("服务器地址：" + url);
        RequestMapping requestMappingClass = ApiTest.class.getAnnotation(RequestMapping.class);
        String mainPath = requestMappingClass.value()[0];
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get(ApiTest.class.getName());
        CtMethod[] methods = cc.getDeclaredMethods();
        for (CtMethod method : methods) {
            RequestMapping requestMapping = (RequestMapping) method.getAnnotation(RequestMapping.class);
            System.out.println("接口:" + requestMapping.name());
            System.out.println("url:" + mainPath + requestMapping.value()[0]);
            // 使用javaassist的反射方法获取方法的参数名
            MethodInfo methodInfo = method.getMethodInfo();
            CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
            LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
            if (attr == null) {
                // exception
            }
            String[] paramNames = new String[method.getParameterTypes().length];
            int pos = Modifier.isStatic(method.getModifiers()) ? 0 : 1;
            for (int i = 0; i < paramNames.length; i++) {
                paramNames[i] = attr.variableName(i + pos);
            }
            String param = "";
            for (int i = 0; i < paramNames.length; i++) {
                param += paramNames[i] + ",";
            }
            if (SysUtil.isEmpty(param)) {
                param = "不需要,";
            }
            System.out.println("参数：" + param.substring(0, param.length() - 1));
            System.out.println("");
        }
    }
}
